/******************************************************************************
 * FILENAME    : SQAUTILS.C
 * PRODUCT    : SoftPay ASPAC Base Application
 * VERSION     : 1.0
 * MODULE      : Utility Module
 * AUTHOR(S)  : Vipin_k1
 * CREATED     : 19-Jul-2000
 *
 * DESCRIPTION : This file shoudl be included by the modules which wish to
 *               utilise the Data Base Module.
 *
 * NOTES       :
 *
 * CONTENTS    :
 *
 *
 * MODIFICATION HISTORY    :
 *
 * #  Date       Who        History
 * -- --------   ---------- ---------------------------------------
 *
 *******************************************************************************
 * Copyright (C) 2000 by VeriFone Inc.
 * All rights reserved. No part of this software may be reproduced,transmitted,
 * transcribed, stored in a retrieval system, or translated into any language
 * or computer language, in any form or by any means, electronic, mechanical,
 * magnetic, optical, chemical, manual or otherwise, without the prior written
 * permission of VeriFone Inc.
 *                                                VeriFone Inc.
 *                                                III Lagoon Drive, Suite 400
 *                                                Redwood City, CA 94065
 ******************************************************************************
 */
//#include <beetle.h>

#include <stdio.h>
#include <string.h>
#include <aclconio.h>
#include <svctxo.h>
#include <printer.h>
#include <stdarg.h>
#include <svc.h>
#include <debug.h>
#include <define.h>
#include <date.h>

#include <transact.h>

#include <multilng.h>
#include <ui.h>

#include "SQAutils.h"
#include "dbfm.h"
#include "msg.h"

#define MAX_HANDLE  30 
#define FNAME_SIZE   10

static void vdCPACPrintErrorLogHeader(TRANSACTION_OBJECT* pobTran);
static int inMaxHandles(void);
extern void vdDisplayAt(int x,int y,const char* m,int o);
extern int inDBFileExists(const char* pszFileName);
extern void vdDisplayErrorMessage(long lnMessageIndex);

typedef struct TagCPACERRLOG {
    char szDate[DATE_SIZE + 1];
    char szTime[TIME_SIZE + 1];
    char szErrorMessage[CPAC_MAX_ERR_MSG_SIZE + 1];
} CPAC_ERROR_LOG;


/******************************************************************************************
Function      : Multiprintf()
Author        : Srini_G1. SQA Team VeriFone BLR
Prototype     : short Multiprintf(shor OutDevice, const char * fmt, ...);

Parameters    :  OutDevice  
                   If value is SQA_MIRAGE_OUTPUT_WINDOW  - Message is displayed in Debug Window of Mirage
                   If value is SQA_PRINTER               - Message is printed in Printer connected to Comm Port 4
                   If value is SQA_FILE_OUTPUT           - Message is stored in File - "SQATest.Log"
                   If value is 'A' to 'Z' or 'a' to 'z' or '1' to '0'          - Message is handled by Beetle.

                 fmt
                   Allows to specify the format in which the message is to be outputted

Returns       :  1 on Success
                 -ve value on Failure
******************************************************************************************/

short Multiprintf(short OutDevice,const char* fmt,...) {
    char msg[SQA_MAX_MESSAGE_SIZE];   
    short rtnVal;

    va_list ap;
    va_start(ap, fmt);

    //Converting the Formatter string to a string
    rtnVal = vsprintf(msg, fmt, ap);
    if (rtnVal < 0)
        return -1;
    va_end(ap);

    //To split the Message into sub messages
    rtnVal = SplitAndPrint(OutDevice, msg);
    if (rtnVal < 0)
        return rtnVal;

    return 1;
}     

/******************************************************************************************
Function      : SplitAndPrint()
Author        : Srini_G1. SQA Team VeriFone BLR
Prototype     : short SplitAndPrint(short OutDevice, char * wrkbuf)

Parameters    :  OutDevice  
                   If value is SQA_MIRAGE_OUTPUT_WINDOW  - Message is displayed in Debug Window of Mirage
                   If value is SQA_PRINTER           - Message is printed in Printer connected to Comm Port 4
                   If value is SQA_FILE_OUTPUT           - Message is stored in File - "SQATest.Log"
                   If value is SQA_BEETLE_TRACE          - Message is handled by Beetle.

                 wrkbuf
                   Formatted buffer to be outputted

Returns       :  1 on Success
                 -ve value on Failure
******************************************************************************************/
short SplitAndPrint(short OutDevice,char* wrkbuf) {
    char tempBuf[SQA_ONE_MESSAGE_SIZE + 5];
    short index;
    short BufferLength; 
    short retVal;

    BufferLength = strlen(wrkbuf);

    index = 0;
    while (BufferLength > index) {
        if ((BufferLength - index) < SQA_ONE_MESSAGE_SIZE)
            strcpy(tempBuf, &wrkbuf[index]);
        else {
            memcpy(tempBuf, &wrkbuf[index], SQA_ONE_MESSAGE_SIZE);
            tempBuf[SQA_ONE_MESSAGE_SIZE] = 0;
        }

        retVal = ActualPrintf(OutDevice, tempBuf);
        if (retVal < 0)
            return retVal;
        index += SQA_ONE_MESSAGE_SIZE;
    }

    return 1;
}


/******************************************************************************************
Function      : ActualPrintf()
Author        : Srini_G1. SQA Team VeriFone BLR
Prototype     : short ActualPrintf(short OutDevice, char * msg)

Parameters    :  
                 msg
                   one part of the message that is to be outputted

Returns       :  1 on Success
                 -ve value on Failure
******************************************************************************************/
short ActualPrintf(short OutDevice,char* msg) {
    short hPrinter = 0 ;
    short sRetVal;
    //  static int FirstEntry = 0;
    int inTotalRecs;
    CPAC_ERROR_LOG srCPACErrorLogRec;


    sRetVal = 1;

    if (inDBFileExists(CPAC_ERROR_LOG_FILE) != VS_SUCCESS)
        if (inDBCreateFile(CPAC_ERROR_LOG_FILE, sizeof(srCPACErrorLogRec)) != VS_SUCCESS)
            return(VS_ERROR);
    memset(&srCPACErrorLogRec, 0x00, sizeof(srCPACErrorLogRec));

    vdGetTime(srCPACErrorLogRec.szTime);
    vdGetDate(srCPACErrorLogRec.szDate, DDMMYY);
    if (strlen(msg) > CPAC_MAX_ERR_MSG_SIZE)
        msg[CPAC_MAX_ERR_MSG_SIZE] = 0x00;
    strcpy(srCPACErrorLogRec.szErrorMessage, msg);
    inTotalRecs = inDBTotalRecords(CPAC_ERROR_LOG_FILE);

    if (inTotalRecs >= CPAC_MAX_ERROR_LOG_RECS) {
        /* Delete the first record from the file */
        if (inDBDeleteRecord(CPAC_ERROR_LOG_FILE, SP_FIRST_REC) < 0)
            vdCBAbort(9903);
        if (inDBWriteRecord(CPAC_ERROR_LOG_FILE, inTotalRecs, (unsigned char *) &srCPACErrorLogRec) < 0)
            vdCBAbort(9904);
    }  /* Add the record in the file */
    else {
        if (inDBWriteRecord(CPAC_ERROR_LOG_FILE, (inTotalRecs + 1), (unsigned char *) &srCPACErrorLogRec) < 0)
            vdCBAbort(9991);
    }

    return sRetVal;
}

static void vdCBAbort(int inErrNum) {
    char szMsg[21 + 1];

    sprintf(szMsg, "Err.Code:%d", inErrNum); 
    vdDisplayAt(1, 4, szMsg, CLR_EOL);
    get_char();
}
/*-----------------------------------------------------------------------------
* Routine Name : int inCPACPrintLines(unsigned char *buffer, PRINTER_OBJECT *obPrinter)
* Description  : 
* Inputs       : None
* Outputs      : None
* Returns      : VS_SUCCESS/no. of bytes printed
* Notes        : 
*---------------------------------------------------------------------------*/

int inCPACPrintLines(char* pchBuffer,PRINTER_OBJECT* obPrinter) {
    int inChars = 0; //, inLen;
    char szBuffer[50 + 1];

    memset(szBuffer, 0x00, sizeof(szBuffer));
    strncpy(szBuffer, pchBuffer, (sizeof(szBuffer) - 2)); // Making sure that place for \n & \0
    strcat(szBuffer, "\n");
    inChars = p3300_print(obPrinter->inHandle, (unsigned char *) szBuffer);
    return(inChars);
}


/*-----------------------------------------------------------------------------
* Routine Name : int inCPACPrintErrorReport
* Description  : 
* Inputs       : None
* Outputs      : None
* Returns      : VS_SUCCESS/VS_FAILURE
* Notes        : 
*---------------------------------------------------------------------------*/

int inCPACPrintErrorReport(TRANSACTION_OBJECT* pobTran) {
    int inNoBytes;
    unsigned int inNoOfRecs, inNoTotalRecs;
    char szBuf[60 + 1];
    CPAC_ERROR_LOG srCPACErrorLogRec;

    memset((char *) szBuf, 0, sizeof(szBuf));
    if (inDBFileExists(CPAC_ERROR_LOG_FILE) != VS_SUCCESS) {
        inCPACPrintLines("NO ACTIVITIES LOGGED YET!", &obPrinter);
        inCPACPrintLines(" ", &obPrinter);
        inCPACPrintLines(" ", &obPrinter);
        inCPACPrintLines(" ", &obPrinter);
        return(VS_SUCCESS);
    }

    inNoOfRecs = inDBTotalRecords(CPAC_ERROR_LOG_FILE);

    vdCPACPrintErrorLogHeader(pobTran);

    for (inNoTotalRecs = 1; inNoTotalRecs <= inNoOfRecs; ++inNoTotalRecs) {
        memset((char *) szBuf, 0, sizeof(szBuf));

        inNoBytes = inDBReadRecord(CPAC_ERROR_LOG_FILE, inNoTotalRecs, (unsigned char *) &srCPACErrorLogRec);
        if (inNoBytes < 0)
            return (VS_FAILURE);

        sprintf((char *) szBuf, "%02d. %s  %s", inNoTotalRecs, srCPACErrorLogRec.szDate, srCPACErrorLogRec.szTime);
        inCPACPrintLines((char *) szBuf, &obPrinter);
        strcpy(szBuf, "   ");
        strcat(szBuf, srCPACErrorLogRec.szErrorMessage);

        inCPACPrintLines((char *) szBuf, &obPrinter);
        inCPACPrintLines(" ", &obPrinter);
    }

    inCPACPrintLines("*********************", &obPrinter);
    inCPACPrintLines(" ", &obPrinter);
    inCPACPrintLines(" ", &obPrinter);
    inCPACPrintLines(" ", &obPrinter);
    inCPACPrintLines(" ", &obPrinter);

    return(VS_SUCCESS);
}

static void vdCPACPrintErrorLogHeader(TRANSACTION_OBJECT* pobTran) {
    inCPACPrintLines("*********************", &obPrinter);
    inCPACPrintLines(" ACTIVITY LOG REPORT", &obPrinter);
    inCPACPrintLines(" ", &obPrinter);
}

void ACTIVITY_LOG(const char* pszLogMessage) {
    Multiprintf(ERROR_LOG, pszLogMessage);
}

int inCPACFindHandlesLeft(TRANSACTION_OBJECT* pobTran) {
    char szHandles[2 + 1];
    sprintf(szHandles, "%02d", inMaxHandles());
    vdClearNonTitleLines();
    vdDisplayDataStr(szHandles, 4, CLR_EOL, ML_CENTER);
    //      (10, 4, szHandles, CLR_EOL);
    get_char();
    return(VS_SUCCESS);
}
static int inMaxHandles(void) {
    char szFName[FNAME_SIZE + 1];
    int inCnt,
    inCloseCnt,
    ahFHandle[MAX_HANDLE + 1];
    for (inCnt = 0; inCnt < MAX_HANDLE; inCnt++) {
        sprintf(szFName, "File%03d", inCnt);
        ahFHandle[inCnt] = open(szFName, (O_CREAT | O_RDWR));
        if (ahFHandle[inCnt] <= 0)
            break;
    }

    for (inCloseCnt = 0; inCloseCnt <= inCnt; inCloseCnt++)
        close(ahFHandle[inCloseCnt]);
    return(inCnt);
}

//#endif /* #if ERROR_LOG */
